import type { App } from 'vue'
import {
    createRouter,
    createWebHashHistory,
    type RouteRecordRaw
} from 'vue-router'

export const Layout = () => import('@/layout/Layout.vue')

const constantRoutes: RouteRecordRaw[] = [
    {
        path: '/',
        name: '/',
        meta: {},
        redirect: '/medicine',
        component: Layout,
        children: [
            {
                path: '/medicine',
                name: 'medicine',
                meta: { title: '药品管理' },
                component: () => import('@/views/medicine/MedicinePage.vue')
            },
            {
                path: '/demo-component-medicine',
                name: 'demo-component-medicine',
                meta: { title: '选药品组件测试' },
                component: () => import('@/views/demo/MedicineTableComponent.vue')
            }
        ]
    }
]

const router = createRouter({
    history: createWebHashHistory(),
    routes: constantRoutes,
    // 刷新时，滚动条位置还原
    scrollBehavior: () => ({ left: 0, top: 0 })
})

router.beforeEach((to, _, next) => {
    if (to.path === '/') {
        next('/medicine')
    } else {
        if (constantRoutes.some((v) => v.path === to.path)) {
            next('/medicine')
        } else {
            next()
        }
    }
})

// 全局注册 router
export function setupRouter(app: App<Element>) {
    app.use(router)
}

export default router